package com.weixingzh.utils;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;
import java.security.MessageDigest;

@Slf4j
@Component
public class WXTokenInterceptor implements HandlerInterceptor {
    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     * 基于URL实现的拦截器
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */

    @Autowired
    public Const c;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String path = request.getServletPath();
        if (path.matches(Const.NO_INTERCEPTOR_PATH)) {
            //不需要的拦截直接过
            return true;
        } else {
            PrintWriter writer = response.getWriter();
            response.setContentType("application/json; charset=utf-8");

            try {

                // 这写你拦截需要干的事儿，比如取缓存，SESSION，权限判断等
                System.out.println("preHandle works");
                //拦截请求，验证token，校验消息是否来自于微信服务器
                int contentLength = request.getContentLength();
                if (contentLength == 0) {
                    log.info("hello, this is handle view");
                    writer.print("hello, this is handle view");
                    writer.close();
                    return true;
                } else {
                    String signature = request.getParameter("signature");
                    String timestamp = request.getParameter("timestamp");
                    String nonce = request.getParameter("nonce");
                    String echostr = request.getParameter("echostr");
                    String token = c.ACToken;
//                    System.out.println("token: " + token);

                    //进行sha1加密
                    String[] data = new String[] {token, timestamp, nonce};
                    StringBuilder content = new StringBuilder();
                    for (String datum : data) {
                        content.append(datum);
                    }
                    MessageDigest md = null;
                    String result = null;
                    md = MessageDigest.getInstance("SHA-1");
                    // 将三个参数字符串凭借成一个字符串进行sha1加密
                    byte[] tempbyte = md.digest(content.toString().getBytes());
                    result = Const.byteToStr(tempbyte);

                    //判断签名是否正确
                    if (!result.equals(signature)) {
                        //错误则不放行
                        log.info("签名错误！");
//                        writer.println("request failed！");
                        writer.append(echostr);
                        writer.close();
                        return false;
                    }
                    //正确则直接放行
                    System.out.println("preHandle over");

                    writer.append(echostr);
                    writer.close();
                    return true;
                }

            }catch (Exception e) {
                e.printStackTrace();
            } finally {
                writer.close();
                return false;
            }
        }
    }
}